﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Yqd.Controllers.Filter;
using Adp.Common;
using System;
using Yqd.Core;
using Yqd.Enm;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxSpecialTemplateController : Controller
    {
        YqdContext ctx;

        public WxSpecialTemplateController(YqdContext ctx)
        {
            this.ctx = ctx;
        }

        /// <summary>
        /// 添加专项任务模板
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Add(Yqd_SpecialTemplate model)
        {
            ctx.Database.ExecuteSql("update Yqd_SpecialTemplate set IsDq=0 where TaskID={0};", model.TaskID);
            model.Tactic = ctx.Database.MaxID("Yqd_SpecialTemplate", "Tactic");
            model.IsDq = true;
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            ctx.Yqd_SpecialTemplate.Add(model);
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                model.TemplateID,
                ret
            });
        }

        /// <summary>
        /// 添加专项任务模板
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Edit(Yqd_SpecialTemplate model)
        {
            var t = ctx.Yqd_SpecialTemplate.FirstOrDefault(it => it.TemplateID == model.TemplateID);
            if (t != null)
            {
                t.Fields = model.Fields;
                t.oFields = model.oFields;
            }
            var ret = ctx.SaveChanges();
            return this.ToJson(new
            {
                success = true,
                model.TemplateID,
                ret
            });
        }

        /// <summary>
        /// 获取当前专项任务模板
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Get()
        {
            var TaskID = Form.GetInt("TaskID");
            var TaskName = "";
            var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == TaskID);
            if (task != null) TaskName = task.Name;
            var t = ctx.Yqd_SpecialTemplate.FirstOrDefault(it => it.TaskID == TaskID && it.IsDq);
            var TemplateID = 0;
            var Fields = new JArray();
            var oFields = new JObject();
            if (t != null)
            {
                if(t.Fields.HasValue()) Fields = JArray.Parse(t.Fields);
                if (t.oFields.HasValue()) oFields = (JObject)JsonConvert.DeserializeObject(t.oFields);
                TemplateID = t.TemplateID;
            }
            return this.ToJson(new
            {
                success = true,
                TemplateID,
                TaskName,
                Fields,
                oFields
            });
        }

        /// <summary>
        /// 获取当前专项任务模板
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult GetTemplate()
        {
            var TaskID = Form.GetInt("TaskID");
            var TaskName = "";
            var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == TaskID);
            if (task != null) TaskName = task.Name;
            var t = ctx.Yqd_SpecialTemplate.FirstOrDefault(it => it.TaskID == TaskID && it.IsDq);
            var TemplateID = 0;
            var Fields = new List<object>();
            var oFields = new JObject();
            if (t != null)
            {
                if (t.Fields.HasValue()) {
                    var arr = JArray.Parse(t.Fields);
                    foreach(var f in arr)
                    {
                        var ftype = int.Parse(f["FieldType"]?.ToString() ?? "0");
                        var FieldValue = new JArray();
                        var val = f["FieldValue"]?.ToString();
                        if (val.HasValue()) FieldValue=  JArray.Parse(val);
                        Fields.Add(new
                        {
                            FieldID = f["FieldID"]?.ToString(),
                            Name = f["Name"]?.ToString(),
                            FieldType = ftype,
                            FieldValue,
                            DefaultValue = ftype == (int)字段类型.自动生成 ? DateTime.Now.ToString("yyyyMMddHHmmssfff") : "",
                            IsShow = bool.Parse(f["IsShow"]?.ToString() ?? "False")
                        });
                    }
                }
                if (t.oFields.HasValue()) oFields = JObject.Parse(t.oFields);
                TemplateID = t.TemplateID;
            }
            var r = ctx.Database.SqlQuery<Yqd_SpecialStandard>("select * from Yqd_SpecialStandard where TaskID={0} order by Tactic asc", TaskID);
            return this.ToJson(new
            {
                success = true,
                TemplateID,
                TaskName,
                Fields,
                oFields,
                Standards = r.Select(it => new
                {
                    it.StandardID,
                    it.Content
                }),
                AssignLimit = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd")
            });
        }

        [User]
        public ActionResult Delete()
        {
            var TemplateID = Form.GetInt("TemplateID");
            var ret = ctx.Database.ExecuteSql("delete from Yqd_SpecialTemplate where TemplateID={0};", TemplateID);
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        //[User]
        //public ActionResult GetTamplateFile()
        //{
        //    try
        //    {
        //        var TaskID = Form.GetInt("TaskID");
        //        var TypeID = Form.GetInt("TypeID");
        //        var temps = ctx.Yqd_SpecialTemplate.Where(it => it.IsGeneral || (it.TaskID == TaskID && it.TypeID == TypeID));
        //        const string filename = "督查任务模板表.xlsx";
        //        var path = Config.Yqdpath("/sys/xls/");
        //        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        //        FileInfo file = new FileInfo(path + filename);
        //        if (file.Exists) file.Delete();
        //        var title = temps.OrderBy(it => it.Tactic).Select(it => it.Name).ToArray();
        //        using (ExcelPackage package = new ExcelPackage(file))
        //        {
        //            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("督查任务模板");
        //            int index = 1;
        //            foreach (string t in title)
        //            {
        //                worksheet.Cells[1, index].Style.Font.Name = "宋体";
        //                worksheet.Cells[1, index].Style.Font.Bold = true;
        //                worksheet.Cells[1, index].Style.Font.Size = 12;
        //                worksheet.Cells.Style.ShrinkToFit = true;
        //                worksheet.Row(1).Height = 30;
        //                worksheet.Column(index).Width = 20;
        //                worksheet.Row(1).CustomHeight = true;
        //                worksheet.Cells[1, index].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        //                worksheet.Cells[1, index].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
        //                worksheet.Cells[1, index].Value = t;
        //                index++;
        //            }
        //            package.Save();
        //            package.Dispose();
        //            return Json(new
        //            {
        //                success = true,
        //                filepath = "/sys/xls/" + filename
        //            });
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        return Json(new
        //        {
        //            success = false,
        //            ex.Message
        //        });
        //    }
        //}

        //[User]
        //public ActionResult GetTargetList()
        //{
        //    var TaskID = Form.GetInt("TaskID");
        //    var TypeID = Form.GetInt("TypeID");
        //    var page = Form.GetInt("page", 1);
        //    var pagesize = Form.GetInt("pagesize", 0);
        //    var datas = ctx.Yqd_SpecialTarget.Where(it => it.TaskID == TaskID && it.TypeID == TypeID);
        //    var data = new List<object>();
        //    foreach (var d in datas)
        //    {
        //        if (d.Content.HasValue())
        //        {
        //            data.Add(JObject.Parse(d.Content));
        //        }
        //    }
        //    var totalcount = data.Count();
        //    if (pagesize > 0)
        //    {
        //        data = data.Skip((page - 1) * pagesize).Take(pagesize).ToList();
        //    }
        //    return Json(new
        //    {
        //        success = true,
        //        totalcount,
        //        data
        //    });
        //}

        //public ActionResult Import()
        //{
        //    var fn = Form.GetString("fn");
        //    var TaskID = Form.GetInt("TaskID");
        //    var TypeID = Form.GetInt("TypeID");
        //    var path = Config.Yqdpath();
        //    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        //    FileInfo file = new FileInfo(path + fn);
        //    if (file != null)
        //    {
        //        using (ExcelPackage package = new ExcelPackage(file))
        //        {
        //            ExcelWorksheet worksheet = package.Workbook.Worksheets["督查任务模板"];
        //            int rowCount = worksheet.Dimension.Rows;
        //            int ColCount = worksheet.Dimension.Columns;
        //            var headers = worksheet.Cells[1, 1, 1, ColCount].Select(it => it.Text).ToArray();
        //            var fields = ctx.Yqd_SpecialTemplate.Where(it => it.IsGeneral || (it.TaskID == TaskID && it.TypeID == TypeID)).OrderBy(it => it.Tactic).Select(it => new { it.FieldID, it.Name }).ToList();
        //            var record = new Dictionary<string, string>();
        //            for (var row = 2; row <= rowCount; row++)
        //            {
        //                record.Clear();
        //                var model = new Yqd_SpecialTarget();
        //                model.TaskID = TaskID;
        //                model.TypeID = TypeID;
        //                for (var col = 1; col <= ColCount; col++)
        //                {
        //                    var nt = worksheet.Cells[row, col].Value.ToString().Trim();
        //                    var f = fields.FirstOrDefault(it => it.Name.Trim() == headers[col-1].Trim());
        //                    if (f != null)  record.Add(f.FieldID, nt);
        //                }
        //                if (record.Count() > 0) model.Content = JObject.FromObject(record).ToString();
        //                model.Instime = DateTime.Now;
        //                model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
        //                model.UnitCode = WxUser.LogonInfo.UnitCode;
        //                ctx.Yqd_SpecialTarget.Add(model);
        //            }
        //            var ret = ctx.SaveChanges();
        //            return this.ToJson(new
        //            {
        //                success = true,
        //                ret
        //            });
        //        }
        //    }
        //    return this.ToJson(new
        //    {
        //        success = false
        //    });
        //}

        //[User]
        //public ActionResult Clear()
        //{
        //    var TaskID = Form.GetInt("TaskID");
        //    var TypeID = Form.GetInt("TypeID");
        //    var ret = ctx.Database.ExecuteSql("delete from Yqd_SpecialTarget where TaskID={0} and TypeID={1};", TaskID, TypeID);
        //    return this.ToJson(new
        //    {
        //        success = true,
        //        ret
        //    });
        //}
    }
}
